package com.cloudkinto.service.storage.impl;

import com.cloudkinto.common.constant.SysConstant;
import com.cloudkinto.common.utils.StringsUtil;
import com.cloudkinto.dao.ProductStockRackDao;
import com.cloudkinto.dao.StorageDao;
import com.cloudkinto.dao.StorageShelfDao;
import com.cloudkinto.entity.StorageDo;
import com.cloudkinto.entity.StoragePositionDo;
import com.cloudkinto.dao.StoragePositionDao;
import com.cloudkinto.entity.StorageShelfDo;
import com.cloudkinto.extentity.stock.PickupStockRackDto;
import com.cloudkinto.extentity.stock.ProductStockTotalDto;
import com.cloudkinto.service.product.ProductStockRackService;
import com.cloudkinto.service.product.vo.rack.ProductStockRackRes;
import com.cloudkinto.service.storage.StoragePositionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.cloudkinto.common.web.PageResult;
import com.cloudkinto.common.web.SingleResult;

import com.cloudkinto.service.storage.vo.StoragePositionPageRes;
import org.apache.commons.collections.list.AbstractLinkedList;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * service实现类
 * </p>
 *
 * @author zhujiale`
 * @since 2022-12-21
 */
@Service
@Transactional(rollbackFor = Exception.class)//事务回滚
public class StoragePositionServiceImpl extends ServiceImpl<StoragePositionDao, StoragePositionDo> implements StoragePositionService {
    @Autowired
    private StoragePositionDao dao;
    @Autowired
    private StorageShelfDao storageShelfDao;
    @Autowired
    private StorageDao storageDao;
    @Autowired
    private ProductStockRackService productStockRackService;
    @Autowired
    private ProductStockRackDao productStockRackDao;

    @Override
    public SingleResult addInit() {
        return SingleResult.success("");
    }

    @Override
    public Object add(Object req, Long userId) {
        StoragePositionDo entityDo = new StoragePositionDo();
        BeanUtils.copyProperties(req, entityDo);
        handlerAddBefore(entityDo, userId);
        dao.insert(entityDo);
        return handlerAddAfter(entityDo);
    }

    //新增校验
    private void addCheck(Object req) {

    }

    //做新增之前要执行的业务定制处理
    private void handlerAddBefore(StoragePositionDo entityDo, Long userId) {
        entityDo.setCreateBy(userId);
        entityDo.setCreateTime(new Date());
    }

    //将新增的do转换成要返回的实体
    private Object handlerAddAfter(StoragePositionDo entityDo) {
        Object res = new Object();
        BeanUtils.copyProperties(entityDo, res);
        return res;
    }

    @Override
    public SingleResult updateInit(Long id) {
        return SingleResult.success("");
    }

    @Override
    public Object update(Object req, Long userId) {
        /*StoragePositionDo entityDo = dao.selectById(req.getId());
        BeanUtils.copyProperties(req, entityDo);
        handlerUpdateBefore(entityDo, userId);
        dao.updateById(entityDo);
        return handlerUpdateAfter(entityDo);*/
        return null;
    }

    //编辑校验
    private void updateCheck(Object req) {

    }

    //做修改之前要执行的业务定制处理
    private void handlerUpdateBefore(StoragePositionDo entityDo, Long userId) {
        entityDo.setUpdateBy(userId);
        entityDo.setUpdateTime(new Date());
    }

    //做修改之后要执行的业务定制处理
    private Object handlerUpdateAfter(StoragePositionDo entityDo) {
        Object res = new Object();
        BeanUtils.copyProperties(entityDo, res);
        return res;
    }

    @Override
    public int delete(Long id, Long userId) {
        StoragePositionDo entityDo = dao.selectById(id);
        handlerDeleteBefore(entityDo, userId);
        return dao.deleteById(id);
    }

    //做删除之前要执行的业务定制处理
    private void handlerDeleteBefore(StoragePositionDo entityDo, Long userId) {

    }

    @Override
    public Object detail(Long id) {
        StoragePositionDo entityDo = dao.selectById(id);
        Object res = new Object();
        BeanUtils.copyProperties(entityDo, res);
        return handlerDetailAfter(res);
    }

    //查询明细之后要执行的业务定制处理
    private Object handlerDetailAfter(Object res) {
        return res;
    }

    @Override
    public SingleResult pageInit() {
        return SingleResult.success("");
    }


    @Override
    public PageResult getListPage(Map<String, String> map) {
        StorageShelfDo shelfDo = storageShelfDao.selectById(map.get("id"));
        QueryWrapper<StoragePositionDo> wrapper = queryBuild(map);
        IPage<StoragePositionDo> page = pageInit(map);
        page = this.page(page, wrapper);
        List<StoragePositionDo> resultList = page.getRecords();
        List<StoragePositionPageRes> resList = new ArrayList<>();
        for (StoragePositionDo et : resultList) {
            StoragePositionPageRes res = new StoragePositionPageRes();
            BeanUtils.copyProperties(et, res);
            res.setStockCapacity(shelfDo.getStockCapacity());
            res.setTypeCN(StringsUtil.createI18Message(shelfDo.getType() == 1 ? SysConstant.StorageShelf_SMALL : SysConstant.StorageShelf_Big));
            res.setStatusCN(StringsUtil.createI18Message(shelfDo.getStatus() == 1 ? SysConstant.Enable : SysConstant.Unable));
            StorageDo storageDo = storageDao.selectById(shelfDo.getStorageId());
            if (null != storageDo) {
                res.setStorageCN(storageDo.getStorageName());
            }
            resList.add(res);
        }
        PageResult result = new PageResult(resList, (int) page.getCurrent(), (int) page.getSize(), (int) page.getTotal(), (int) page.getPages());
        return result;
    }


    private IPage<StoragePositionDo> pageInit(Map<String, String> map) {
        IPage<StoragePositionDo> page = new Page();
        page.setSize(StringUtils.isNotBlank(map.get("pageSize")) ? Long.parseLong(map.get("pageSize")) : 10);
        page.setCurrent(StringUtils.isNotBlank(map.get("current")) ? Long.parseLong(map.get("current")) : 1);
        return page;
    }

    private QueryWrapper<StoragePositionDo> queryBuild(Map<String, String> map) {
        QueryWrapper<StoragePositionDo> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(map.get("shelfName"))) {
            wrapper.like("position_name", map.get("shelfName"));
        }
        wrapper.eq("shelf_id", map.get("id"));
        return wrapper;
    }


    /**
     * 入库 库位 初始化 获取库位信息
     * @param storageId
     * @param companyId
     * @param productId
     * @param store
     * @param type
     * @param containBad 0 不包含 不可售库存 1 包含不可售库存
     * @return
     */
    @Override
    public Map<String, Object> getPosition(Long storageId, Long companyId, Long productId, int store, int type, int containBad) {
        Map<String, String> param = new HashMap<>();
        param.put("storageId", storageId +"");
        if (companyId != null) {
            param.put("companyId", companyId + "");
        }
        param.put("productId", productId + "");
        param.put("store", store + "");
        param.put("type", type +"");//库存大于 0
        param.put("containBad", containBad+"");

        Map<String, Object> result = new HashMap<>();
        if (type == 0) {
            //获取所有库位 入库时用
            List<StorageShelfDo> shelfList = storageShelfDao.selectList(new QueryWrapper<StorageShelfDo>().eq("storage_id", storageId));
            List<Map<String, Object>> positionMapList = new ArrayList<>();
            List<Map<String, Object>> shelfMapList = new ArrayList<>();
            Map<String, Object> defaultMap = new HashMap<>();
            defaultMap.put("rackId", null);
            defaultMap.put("value", "默认库位");
//            defaultMap.put("goodQuantity", defaultQuantity);
            positionMapList.add(defaultMap);


            for (StorageShelfDo et : shelfList) {
                //货架信息
                Map<String, Object> shelfMap = new HashMap<>();
                shelfMap.put("shelfId", et.getId());
                shelfMap.put("value", et.getShelfName());
                shelfMapList.add(shelfMap);

                List<StoragePositionDo> positionList = dao.selectList(new QueryWrapper<StoragePositionDo>().eq("shelf_id", et.getId()));
                for (StoragePositionDo pt : positionList.stream()
                        .filter(storagePositionDo -> StringUtils.isNotBlank(storagePositionDo.getPositionName()))
                        .sorted(new Comparator<StoragePositionDo>() {
                            @Override
                            public int compare(StoragePositionDo o1, StoragePositionDo o2) {
                                return o1.getPositionName().compareTo(o2.getPositionName());
                            }
                        }).collect(Collectors.toList())) {
                    Map<String, Object> map = new HashMap<>();
                    map.put("rackId", pt.getId());
                    map.put("value", pt.getPositionName());
                    map.put("shelfId", et.getId());
                    //获取剩余库存
                    positionMapList.add(map);
                }
            }
            result.put("positionList", positionMapList);
            result.put("shelfList", shelfMapList);
        }
        else {
            //出库 库存时，获取有库存得库位
            List<ProductStockTotalDto> stockRackList;
            //倒序获取库位货存 可做到先进先出
            synchronized (this) {
                stockRackList = productStockRackDao.getStockRackTotalBySort(param);
            }
            List<Map<String, Object>> positionMapList = new ArrayList<>();

            for (ProductStockTotalDto stockRackDo : stockRackList) {
                Map<String, Object> map = new HashMap<>();
                map.put("rackId", stockRackDo.getRackId());
                map.put("value",  stockRackDo.getRackId() == null ? "默认库位" : stockRackDo.getPositionName());
                map.put("positionName",  stockRackDo.getRackId() == null ? "默认库位" : stockRackDo.getPositionName());
                map.put("shelfId", stockRackDo.getShelfId());
                map.put("goodQuantity", containBad == 0 ? stockRackDo.getGoodQuantity() : stockRackDo.getBadQuantity());
                positionMapList.add(map);
            }
            result.put("positionList", positionMapList);
        }
        return result;
    }

}
